/*******************************************************************************
 * Package: com.hngtrust.iir.user.service.impl
 * Type:    TagServiceImpl
 * Date:    2021/5/20 17:26
 *
 * Copyright (c) 2021 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.hngtrust.iir.user.service.impl;

import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hngtrust.iir.constant.Constant;
import com.hngtrust.iir.elk.exception.ElkErrorType;
import com.hngtrust.iir.elk.exception.ElkException;
import com.hngtrust.iir.user.controller.dto.ListSelfTagReqVO;
import com.hngtrust.iir.user.entity.SelfTag;
import com.hngtrust.iir.user.service.SelfTagService;
import com.hngtrust.iir.user.service.TagService;
import com.hngtrust.iir.util.ElkUtils;
import com.tiger.util.MyHttpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

/**
 * 标签管理
 *
 * @author Keqiwei
 * @date 2021/5/20 17:26
 */
@Slf4j
@Service
public class TagServiceImpl implements TagService {
    
    @Value("${elk.search.url:}")
    private String elkUrl;
    
    @Autowired
    private SelfTagService selfTagService;
    
    @Override
    public List<SelfTag> queryList(ListSelfTagReqVO vo) {
        SelfTag selfTag = new SelfTag();
        selfTag.setStatus(Constant.DEFAULT_STATUS_NORMAL);
        BeanUtils.copyProperties(vo,selfTag);
       return selfTagService.queryList(selfTag);
    }
    
    @Override
    public String getElkId(String indexName, String id) {
        MyHttpClient myHttpClient = new MyHttpClient();
        ObjectMapper objectMapper = new ObjectMapper();
        String elkSearchUrl = getElkSearchUrl(indexName);
        JSONObject infoParams = getInfoParams(id);
        String json = myHttpClient.postJson(elkSearchUrl, infoParams);
        try {
            JsonNode jsonNode = objectMapper.readTree(json);
            return getId(jsonNode);
        }catch (Exception e){
            log.error("ELK检索新闻资讯索引地址:{}异常:{}", elkSearchUrl, e);
            throw new ElkException(ElkErrorType.ELK_SEARCH_INDEX_EXCEPTION, elkSearchUrl);
        }
    }
    
    
    private JSONObject getInfoParams(String id){
        JSONObject query = new JSONObject();
        JSONObject compId = new JSONObject();
        compId.put(ElkUtils.ELK_IIR+"."+ElkUtils.ELK_IIR_CLICKHOUSEID,id);
        JSONObject match = new JSONObject();
        match.put(ElkUtils.ELK_GRAMMAR_MATCH_PHRASE,compId);
        query.put(ElkUtils.ELK_GRAMMAR_QUERY,match);
        return query;
    }
    
    private String getElkSearchUrl(String indexName) {
        String url = null;
        if (jodd.util.StringUtil.isBlank(elkUrl) || jodd.util.StringUtil.isBlank(indexName)) {
            log.error("elk检索地址{}为空，或索引{}空",elkUrl,indexName);
            return null;
        }
        if (elkUrl.endsWith("/") || elkUrl.endsWith("\\")) {
            url = elkUrl + indexName + "/" + ElkUtils.ELK_GRAMMAR_SEARCH;
        } else {
            url = elkUrl + "/" + indexName + "/" + ElkUtils.ELK_GRAMMAR_SEARCH;
        }
        return url;
    }
    
    
    private String getId(JsonNode jsonNode){
        JsonNode parentHits = jsonNode.get(ElkUtils.ELK_HITS);
        if(null == parentHits) {
            log.error("elk检索内容为空");
            return null;
        }
        JsonNode hits = parentHits.get(ElkUtils.ELK_HITS);
        if (null == hits) {
            log.error("elk检索hits内容为空");
            return null;
        }
        
        String elkId = null;
        
        Iterator<JsonNode> iterator = hits.iterator();
        while (iterator.hasNext()) {
            elkId=iterator.next().get(ElkUtils.ELK_ID).asText();
        }
        return elkId;
    }
}
